package com.xiaozheng.dao;

import com.xiaozheng.daomain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
 * @Package: com.xiaozheng.dao
 * @ClassName: UserDao
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/9/18 13:56
 * @What_is_this_file_for: mybatis注解开发
 * @Description: CRUD 分别对应 @Insert @Delect @Upadte @Select
 */
//开启（使用）二级缓存
@CacheNamespace(blocking = true)
public interface UserDao {
    /**
     * 查询所有用户
     * @return
     */

    @Select("select * from user")
    //配置属性与表字段的映射
    @Results(id = "userMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "address",property = "address"),
            @Result(column = "sex",property = "sex"),
            @Result(column = "birthday",property = "birthday"),
            @Result(column = "id",property = "accounts",many=@Many(select = "com.xiaozheng.dao.AccountDao.findById",fetchType = FetchType.LAZY))
    })
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     */
    @ResultMap("userMap")
    @Update("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
    void saveUser(User user);

    /**
     * 更新用户
     * @param user
     */
    @ResultMap("userMap")
    @Update("update user set username = #{username},address = #{address},sex = #{sex},birthday = #{birthday}  where id = #{id}")
    void updateUser(User user);

    /**
     * 根据id删除用户
     * @param uid
     */
    @ResultMap("userMap")
    @Delete("delete from user where id = #{uid}")
    void deleteUser(Integer uid);

    /**
     * 根据id查找一条数据
     * @param uid
     * @return
     */
    @ResultMap("userMap")
    @Select("select * from user where id = #{uid}")
    User findById(Integer uid);


    /**
     * 根据用户名模糊查找数据
     * @param username
     * @return
     */
    @ResultMap("userMap")
    @Select("select * from user where username like #{username}")
    List<User> findByName(String username);


    /**
     * 查询总记录数
     * @return
     */
    @ResultMap("userMap")
    @Select("select count(*) from user")
    int findTotalUser();
}
